﻿
using UnityEngine;

public class AdsorbExamples : MonoBehaviour
{
    public GameObject curObj;
    public GameObject tagObj;
    Vector3 curVec;
    public float Distan;
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            UpObj();
        }
        if (Input.GetMouseButtonUp(0))
        {
            tagObj.GetComponent<BoxCollider>().enabled = true;
           DownObj();
        }
        if (Input.GetMouseButton(0))
        {
            moveObj();
            DownObj();
        }
    }

    void UpObj()
    {
        tagObj = GetRayGame(out curVec);
        if (tagObj)
        {
            tagObj.GetComponent<BoxCollider>().enabled = false;
        }

    }
    void moveObj()
    {
        curObj = GetRayGame(out curVec);
        if (curObj)
        {
            tagObj.transform.position = curVec;
        }
    }
    void DownObj()
    {
      
        curObj = GetRayGame(out curVec);
        if (curObj)
        {
            Mesh mesh = curObj.GetComponent<MeshFilter>().mesh;

            for (int i = 0; i < mesh.vertexCount; i++)
            {
               
                Vector3 vector = new Vector3(mesh.vertices[i].x * curObj.transform.localScale.x, mesh.vertices[i].y * curObj.transform.localScale.y, mesh.vertices[i].z * curObj.transform.localScale.z) + curObj.transform.position;
                float my_Distance = Vector3.Distance(vector, tagObj.transform.position);
                Debug.Log(vector);

                if (my_Distance < Distan)
                {
                    tagObj.transform.position = vector;
                    return;
                }
            }
        }
    }

    GameObject GetRayGame(out Vector3 vector3)
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit raycastHit;
        GameObject my_GameObject = null;
        if (Physics.Raycast(ray, out raycastHit))
        {
            vector3 = raycastHit.point;
            my_GameObject = raycastHit.collider.gameObject;
        }
        else
        {
            vector3 = Input.mousePosition;
        }
        return my_GameObject;
    }
}
